﻿using System.Globalization;
using System.Web;
using Orchard.Environment.Extensions;
using Orchard.Localization.Services;

namespace Vitus.Localization.Selectors
{
    [OrchardFeature("Vitus.FirstRequestPathPartCultureSelector")]
    public class FirstRequestPathPartCultureSelector : ICultureSelector
    {
        public CultureSelectorResult GetCulture(HttpContextBase context)
        {
            if (context == null)
            {
                return null;
            }

            string requestPath = context.Request.Path.TrimStart('/');
            int slashIndex = requestPath.IndexOf('/');

            if (slashIndex == -1)
            {
                return null;
            }

            string firstRequestPathPart = requestPath.Substring(0, slashIndex);

            try
            {
                var cultureInfo = CultureInfo.GetCultureInfo(firstRequestPathPart);
                return new CultureSelectorResult { Priority = 9, CultureName = cultureInfo.Name };
            }
            catch
            {
                return null;
            }
        }
    }
}